<template>
  <div>
    <images
      :dialog-images="showImages"
      :use-btn="true"
      :use-type="'img'"
      @close="uploadImg"
    />
    <quill-editor
      ref="newEditor"
      v-model="editorContent"
      :options="newOption"
      style="background:#fff;"
      :style="`width:${widths}`"
      @change="editorChange"
    >
    </quill-editor>
    <form
      id="uploadFormMulti"
      action=""
      method="post"
      enctype="multipart/form-data"
      style="display: none"
    >
      <input
        id="uniqueId"
        style="display: none"
        type="file"
        name="avator"
        multiple
        accept="image/jpg,image/jpeg,image/png,image/gif"
        @change="uploadImg('uploadFormMulti')"
      />
      <!-- <video src=''></video> -->
    </form>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import Quill from "quill";
import { ImageImport } from "./modules/ImageImport.js";
import { ImageResize } from "./modules/ImageResize.js";
import images from "../imgupdate";
Quill.register("modules/imageImport", ImageImport);
Quill.register("modules/imageResize", ImageResize);

const handlers = {
  shadeBox: null,
  sourceEditor: function() {
    const container = this.container;
    const firstChild = container.nextElementSibling.firstChild;
    if (!this.shadeBox) {
      let shadeBox = (this.shadeBox = document.createElement("div"));
      let shadeBoxBtn = document.createElement("div");
      shadeBox.appendChild(shadeBoxBtn);
      shadeBox.style.cssText =
        "position:absolute; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); cursor:pointer;";
      container.style.position = "relative";
      shadeBoxBtn.style.cssText =
        "width:64px; border:1px solid #ccc; border-radius:5px;background:#fff;text-align: center; margin: 6px;float: right;";
      shadeBoxBtn.innerText = "返 回";
      shadeBoxBtn.addEventListener(
        "click",
        () => {
          this.shadeBox.style.display = "none";
          firstChild.innerHTML = firstChild.innerText.trim();
        },
        false
      );
      container.appendChild(shadeBox);
      firstChild.innerText = firstChild.innerHTML;
    } else {
      this.shadeBox.style.display = "block";
      firstChild.innerText = firstChild.innerHTML;
    }
  }
};

export default {
  components: { quillEditor, images },
  props: {
    text: {
      type: String,
      default: ""
    },
    widths: {
      type: String,
      default: "100%"
    },
    heights: {
      type: String,
      default: "300px"
    }
  },
  data() {
    return {
      showImages: false,
      editorContent: "",
      imgPercent: 0,
      newOption: {
        placeholder: "请填写描述",
        history: {
          delay: 100,
          maxStack: 100,
          userOnly: false
        },
        modules: {
          toolbar: {
            container: [
              ["bold"],
              ["italic"],
              ["underline"],
              ["strike"],
              ["blockquote"],
              ["code-block"],
              [{ list: "ordered" }],
              [{ list: "bullet" }],
              [{ script: "sub" }],
              [{ script: "super" }],
              [{ indent: "-1" }],
              [{ indent: "+1" }],
              [{ direction: "rtl" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }],
              [{ background: [] }],
              [{ font: [] }],
              [{ align: [] }],
              ["link"],
              ["image"],
              ["sourceEditor"]
            ],
            handlers: handlers
          },
          imageImport: true,
          imageResize: {
            displaySize: true
          }
        }
      }
    };
  },
  computed: {},
  watch: {
    text() {
      this.editorContent = this.text;
    }
  },
  created() {
    this.imgPercent = 0;
    this.editorContent = this.text;
  },
  mounted() {
    this.$refs.newEditor.quill.container.style.height = this.heights;
    const titleConfig = {
      "ql-bold": "加粗",
      "ql-color": "颜色",
      "ql-font": "字体",
      "ql-code": "插入代码",
      "ql-italic": "斜体",
      "ql-link": "添加链接",
      "ql-background": "背景颜色",
      "ql-size": "字体大小",
      "ql-strike": "删除线",
      "ql-script": "上标/下标",
      "ql-underline": "下划线",
      "ql-blockquote": "引用",
      "ql-header": "标题",
      "ql-indent": "缩进",
      "ql-list": "列表",
      "ql-align": "文本对齐",
      "ql-direction": "文本方向",
      "ql-code-block": "代码块",
      "ql-formula": "公式",
      "ql-image": "图片",
      "ql-clean": "清除字体样式",
      "ql-sourceEditor": "编辑源码"
    };
    const oToolBar = document.querySelector(".ql-toolbar");
    const aButton = oToolBar.querySelectorAll("button");
    const aSelect = oToolBar.querySelectorAll("select");
    aButton.forEach(item => {
      if (item.className === "ql-script") {
        item.value === "sub" ? (item.title = "下标") : (item.title = "上标");
      } else if (item.className === "ql-indent") {
        item.value === "+1"
          ? (item.title = "向右缩进")
          : (item.title = "向左缩进");
      } else {
        item.title = titleConfig[item.classList[0]];
      }
      if (item.className === "ql-sourceEditor") {
        item.classList.add("el-icon-edit-outline");
        item.style.fontSize = "16px";
        item.style.fontWeight = "bold";
      }
    });
    aSelect.forEach(item => {
      item.parentNode.title = titleConfig[item.classList[0]];
      // let data = Array.prototype.slice.call(item.children)
      // let arr = [1, 2, 3, 4]
      // item.childre.innerHTML = '<option value='23'>添加成功</option>'
      // data.forEach((ele, i) => {
      //   if (item.classList[0] === 'ql-size') {
      //   }
      // })
    });
    this.$refs.newEditor.quill.getModule("toolbar").addHandler("image", () => {
      this.showImages = true;
    });
  },
  methods: {
    editorChange({ html }) {
      this.$emit("editorChange", html);
    },
    uploadImg(formData) {
      this.showImages = false;
      if (!formData) return;
      const url = this.$store.state.qiniu + formData.file_path;
      let value = url;

      try {
        if (url != null && url.length > 0) {
          value = value.indexOf("http") !== -1 ? value : "http:" + value;
          let index = this.$refs.newEditor.quill.selection.savedRange.index;
          this.$refs.newEditor.quill.insertEmbed(
            index,
            "image",
            value,
            Quill.sources.USER
          );
          var img = new Image();
          img.src = value;
          this.$refs.newEditor.quill.formatText(
            index,
            index + 1,
            "width",
            400 + "px"
          );
        }
        document.getElementById("uniqueId").value = "";
      } catch ({ message: msg }) {
        document.getElementById("uniqueId").value = "";
      }
    }
  }
};
</script>
<style>
.ql-formats {
  line-height: 24px;
}
.ql-snow .ql-editor img {
  margin-top: -5px;
}
</style>
